<?php

namespace app\index\controller;

use app\common\JwtHelper;
use app\index\job\JobActivity;
use app\middleware\SecurityMiddleware;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;
use uploadImg\imgcompress;

/**
 * 萌宝AI小程序接口
 * */
class Ai extends Controller
{
    public function __construct()
    {
        parent::__construct();

        // 调用中间件
        $middleware = new SecurityMiddleware();
        $request = Request::instance();
        $middleware->handle($request, function ($req) {
            // 仅执行验证，不做中间件链路回调
            return response(); // 返回空响应对象用于中间件添加响应头
        });
    }

    public static function authorizationGetOpenid()
    {
        $request = request(); // 获取当前请求

        $authHeader = $request->header('authorization', '');

        if ($authHeader && stripos($authHeader, 'Bearer ') === 0) {
            $token = substr($authHeader, 7);
            $payload = JwtHelper::verifyToken($token);

            if ($payload && !empty($payload['openid'])) {
                // 可选：自动续期（设置响应头，供中间件读取）
                if (JwtHelper::shouldRefreshToken($payload)) {
                    $newToken = JwtHelper::createToken(['openid' => $payload['openid']]);
                    header('X-Refreshed-Token: ' . $newToken);
                }
            }
        }
        return $payload['openid'] ? : '';
    }

    /**
     * 获取token
     * */
    public function getLoginToken()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(httpsRequest($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, '登录失败');

        $user_info = Db::name('user')->where('openid', $openid)->find();
        if ($user_info) {
            $token = JwtHelper::createToken(['openid' => $openid]);
            apiReturn(1, '登录成功', $token);
        } else {
            apiReturn(2, '新用户，走注册流程');
        }
    }

    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = get_access_token('ai_access_token.json', 1);
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                apiReturn(1, '获取数据成功', $mobile);
            } else {
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }


    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $json_res = httpsRequest($url);
        $user_data = json_decode($json_res);

        if ($openid = $user_data->openid) {
            apiReturn(1, '获取数据成功', $openid);
        } else {
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();

        $openid = $input['openid'];
        $avatar = $input['avatar'];
        $nickname = $input['nickname'];
        $mobile = $input['mobile'];

        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($avatar)) apiReturn(2, '请上传头像信息');
        if (empty($nickname)) apiReturn(2, '请填写昵称');
        if (empty($mobile)) apiReturn(2, '请获取手机号');

        $mobile_count = Db::name('user')->where(['mobile' => $mobile])->count();
        if ($mobile_count > 0) apiReturn(2, '该手机号已使用');

        Db::startTrans();
        try {
            $count = Db::name('user')->where(['openid' => $openid])->count();
            if ($count == 0) {
                $data = [
                    'openid' => $openid,
                    'avatar' => str_replace(getHost(), '', $avatar),
                    'username' => $nickname,
                    'mobile' => $mobile,
                    'create_time' => time()
                ];

                Db::name('user')->insert($data);
            }

            Db::commit();

            $token = JwtHelper::createToken(['openid' => $openid]);
            apiReturn(1, '登录成功', $token);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 获取用户信息
     * */
    public function userCenter()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,avatar,username,level,integral')->where(['openid' => $openid])->find();
        if ($info) {
            if ($info['status'] == 2) apiReturn(2, '您的账号已被禁用，请联系管理员');

            $info['avatar'] = $info['avatar'] ? getHost() . $info['avatar'] : '';
            $info['level_desc'] = doUserLevel($info['level']);

            // 礼物数量
            $info['gift_count'] = Db::name('user_gift_log')->where(['user_id' => $info['id']])->count();
            // 我的推广
            $info['spread_count'] = Db::name('user')->where(['up_user_id' => $info['id']])->count();

            $info['format_integral'] = number_format($info['integral']);

            cache($openid, $info['id']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户数据不存在');
        }
    }

    /**
     * 首页
     * */
    public function index()
    {
        $count = rand(500, 5000);

        $data = [
            'count' => $count,
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 礼物列表
     * */
    public function giftLogList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = cache($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('user_gift_log')->where(['user_id' => $user_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['gift_img'] = $v['gift_img'] ? getHost() . $v['gift_img'] : '';
                $v['voice_id'] = pathinfo($v['music_path'], PATHINFO_FILENAME);
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }


    /**
     * 我的收益
     * */
    public function integralLogList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = cache($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $user_info = Db::name('user')->field('integral,payment_qr')->where(['id' => $user_id])->find();
        $list = Db::name('user_integral_log')->where(['user_id' => $user_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['format_time'] = formatRelativeTime($v['create_time']);
            }
        }

        $integral = $user_info['integral'];

        $withdrawal_rate = C('WITHDRAWAL_RATE');// 提现1元需要多少积分

        $apply_withdrawal_count = C('APPLY_WITHDRAWAL_COUNT');  // 每日可申请提现次数
        $min_withdrawal_integral = C('MIN_WITHDRAWAL_INTEGRAL');// 单次最低提现积分


        $data = [
            'withdrawal_tips' => C('WITHDRAWAL_TIPS'),
            'integral' => $integral,
            'format_integral' => number_format($integral),
            'payment_qr' => $user_info['payment_qr'] ? getHost() . $user_info['payment_qr'] : '',
            'integral_price' => sprintf('%.2f', $integral / $withdrawal_rate),
            'apply_withdrawal_count' => $apply_withdrawal_count,
            'min_withdrawal_integral' => $min_withdrawal_integral,
            'list' => $list ? : []
        ];

        apiReturn(1, $list ? '获取数据成功' : '暂无更多数据', $data);
    }

    /**
     * 设置微信收款码
     * */
    public function setPaymentQr()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = cache($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $payment_qr = $input['payment_qr'];

        if (empty($payment_qr)) apiReturn(2, '请上传微信收款码');

        $res = Db::name('user')->where(['id' => $user_id])->setField('payment_qr', str_replace(getHost(), '', $payment_qr));
        if ($res) {
            apiReturn(1, '设置成功');
        } else {
            apiReturn(2, '设置失败');
        }
    }

    /**
     * 申请提现
     * */
    public function applyWithdrawal()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = cache($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $need_integral = $input['integral'];
        if ($need_integral <= 0) apiReturn(2, '请输入正确的提现积分');

        $min_withdrawal_integral = C('MIN_WITHDRAWAL_INTEGRAL');// 单次最低提现积分
        if ($need_integral < $min_withdrawal_integral) apiReturn(2, '单次最低提现积分' . $min_withdrawal_integral);

        if ($need_integral % 1000 > 0) apiReturn(2, '提现积分必须为1000的倍数');

        $user_info = Db::name('user')->field('payment_qr,integral')->where(['id' => $user_id])->find();

        if (!$user_info['payment_qr']) apiReturn(2, '请先设置收款二维码');

        $integral = $user_info['integral'];

        if ($integral < $need_integral) apiReturn(2, '您的积分不足');


        $start_time = strtotime(date('Y-m-d', time()));
        $end_time = strtotime(date('Y-m-d', time() + 86400)) - 1;

        $apply_withdrawal_count = C('APPLY_WITHDRAWAL_COUNT');  // 每日可申请提现次数

        $apply_count = Db::name('user_withdrawal_log')->where(['user_id' => $user_id])->whereBetween('create_time', [$start_time, $end_time])->count();
        if ($apply_count >= $apply_withdrawal_count) apiReturn(2, '您今日的提现次数已用完');

        $withdrawal_rate = C('WITHDRAWAL_RATE');
        $withdrawal_data = [
            'user_id' => $user_id,
            'use_integral' => $need_integral,
            'price' => $need_integral / $withdrawal_rate,
            'create_time' => time()
        ];
        $withdrawal_id = Db::name('user_withdrawal_log')->insertGetId($withdrawal_data);

        $res = doIntegral($user_id, 0 - $need_integral, 'withdrawal', $withdrawal_id, 'ai_user_withdrawal_log', '积分提现');
        if ($res) {
            apiReturn(1, '申请提现成功');
        } else {
            apiReturn(2, '申请提现失败');
        }
    }

    /**
     * 推广列表
     * */
    public function spreadList()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = cache($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('user')->where(['up_user_id' => $user_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = $v['avatar'] ? getHost() . $v['avatar'] : '';
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i');
            }
        }

        $count = Db::name('user')->where(['up_user_id' => $user_id])->count();

        $data = [
            'count' => $count,
            'list' => $list ? : []
        ];

        apiReturn(1, $list ? '获取数据成功' : '暂无更多数据', $data);
    }

    /**
     * 分享数据
     * */
    public function shareData()
    {
        $music_list = Db::name('music')->select();
        if ($music_list) {
            foreach ($music_list as &$v) {
                $v['voice_id'] = pathinfo($v['file_path'], PATHINFO_FILENAME);
                $v['file_path'] = getHost() . $v['file_path'];
            }
        }

        $gift_list = Db::name('gift')->select();
        if ($gift_list) {
            foreach ($gift_list as &$v) {
                $v['img'] = $v['img'] ? getHost() . $v['img'] : '';
            }
            $gift_list = array_chunk($gift_list, 4);
        }

        $withdrawal_rate = C('WITHDRAWAL_RATE');// 提现1元需要多少积分

        $data = [
            'music_list' => $music_list,
            'gift_list' => $gift_list,
            'withdrawal_rate' => intval($withdrawal_rate),
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 支付礼物费用
     * */
    public function payGift()
    {
        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = cache($openid);
        if (empty($user_id)) apiReturn(401, '您还未登录，请先登录');

        $input = Request()->param();

        $content = $input['content'];
        $gift_id = $input['gift_id'];
        $use_integral = $input['use_integral'] ? : 0;
        $use_price = $input['use_price'] ? : 0;
        $use_ad_id = $input['use_ad_id'] ? : 0;
        $music_path = $input['music_path'] ? : '';
        $music_title = $input['music_title'] ? : '';

        $gift_info = Db::name('gift')->where(['id' => $gift_id])->find();
        if (empty($gift_info)) apiReturn(2, '特效不存在');

        $gift_file_path = $gift_info['file_path'];
        if (!$gift_file_path) apiReturn(2, '特效信息有误');

        $gift_file_name = pathinfo($gift_file_path, PATHINFO_FILENAME);
        $gift_effects = intval($gift_file_name);
        if ($gift_info['effects'] == -1) apiReturn(2, '特效文件命名错误');

        Db::startTrans();
        try {
            $data = [
                'user_id' => $user_id,
                'content' => $content,
                'gift_img' => $gift_info['img'],
                'gift_name' => $gift_info['name'],
                'gift_integral' => $gift_info['integral'],
                'gift_effects' => $gift_effects,
                'use_integral' => $use_integral,
                'use_price' => $use_price,
                'use_ad_id' => $use_ad_id,
                'music_path' => $music_path,
                'music_title' => $music_title,
                'create_time' => time(),
            ];
            $gift_log_id = Db::name('user_gift_log')->insertGetId($data);
            if (!$gift_log_id) {
                Db::rollback();
                apiReturn(2, '支付失败');
            }

            if ($use_integral) doIntegral($user_id, 0 - $use_integral, 'buy_gift', $gift_log_id, 'ai_user_gift_log', '购买特效');

            Db::commit();
            apiReturn(1, '支付成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '支付失败' . $e->getMessage());
        }
    }

    /**
     * 消息列表
     * */
    public function msgList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $openid = self::authorizationGetOpenid();
        if (empty($openid)) apiReturn(401, '您还未登录，请先登录');

        $user_id = cache($openid);
        if (empty($user_id)) apiReturn(2, '用户数据不存在');

        $list = Db::name('msg')->whereIn('user_id', [0, $user_id])->order('id desc')->page($page, $pagesize)->select();
        apiReturn(1, '获取数据成功', $list ? : []);
    }

}